package com.questetra.bpms.android;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONException;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.google.api.client.auth.oauth.OAuthCredentialsResponse;
import com.google.api.client.http.HttpResponseException;
import com.questetra.bpms.android.StatsWidgetProvider.StatsService;

public class WorkitemListActivity extends ListActivity {
    /** {@link WorkitemsJsonParser} */
    private WorkitemsJsonParser parser = new WorkitemsJsonParser();

    /** {@link Handler} */
    private Handler handler = new Handler();

    /** ListAdapter */
    private ArrayAdapter<Workitem> workitems;

    @SuppressWarnings("unused")
    private class ConnectionServiceReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
			// Toast toast = Toast.makeText(getApplicationContext(),
			// "OnReceive",
			// Toast.LENGTH_LONG);
			// toast.show();
        }
    }

    //    private final ConnectionServiceReceiver receiver = new ConnectionServiceReceiver();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.workitem_list);
        workitems = new WorkitemAdapter(this,
                                        R.layout.workitem_list_row,
                                        new ArrayList<Workitem>());
        setListAdapter(workitems);

        Intent intent = this.getIntent();
        String action = intent.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            getAccessToken();

        } else {
            try {
                OAuthService.getInstance().setup(this);
            } catch (NoSettingsException e) {
                Intent settings = new Intent(getApplicationContext(),
                                             SettingsActivity.class);
                startActivity(settings);
                finish();
                return;
            } catch (NoAccessTokenException e) {
                getUnauthorizedToken();
                return;
            }
        }

        reloadList();

        /**
        intent = new Intent(this, ConnectionService.class);
        startService(intent);
        registerReceiver(receiver, new IntentFilter("ConnectionService"));
        */
    }

    /**
     * Unauthorized Tokenの取得
     */
    private void getUnauthorizedToken() {
        final ProgressDialog dialog = ProgressDialog.show(this,
                                                          "",
                                                          "requesting OAuth token");

        handler.post(new Runnable() {
            public void run() {
                String authUrl;
                OAuthService service = OAuthService.getInstance();
                try {
                    OAuthCredentialsResponse credentials = service.getUnauthorizedRequestToken();
                    authUrl = service.getAuthorizeUrl(credentials.token);
                } catch (HttpResponseException e) {
                    Log.w(e.getClass().getCanonicalName(), e);
                    Preferences.removeQbpmsInfo(WorkitemListActivity.this);
                    showAlertDialogAndFinishApplication("Failed OAuth operation. Please check registering consumer secret of this application.");
                    return;
                } catch (IOException e) {
                    Log.w(e.getClass().getCanonicalName(), e);
                    Preferences.removeQbpmsInfo(WorkitemListActivity.this);
                    showAlertDialogAndFinishApplication("Failed to connect to server.");
                    return;
                } finally {
                    dialog.dismiss();
                }

                Intent intent = new Intent(Intent.ACTION_VIEW,
                                           Uri.parse(authUrl));
                startActivity(intent);
            }
        });
    }

    /**
     * Access Token の取得
     */
    private void getAccessToken() {
        Uri uri = this.getIntent().getData();
        if (uri != null && uri.toString().startsWith("qbpms://android")) {
            try {
                OAuthService.getInstance().getAccessToken(uri.toString(), this);
            } catch (IOException e) {
                Log.e("OAuth", e.getMessage(), e);
                showAlertDialogAndFinishApplication("Failed OAuth operation.");
                return;
            }
        }
    }

    /**
     * 一覧の取得
     */
    private void reloadList() {
        final ProgressDialog dialog = ProgressDialog.show(this,
                                                          "",
                                                          "loading data");
        handler.post(new Runnable() {
            public void run() {
                String url = "/API/PE/Workitem/listAllocated";

                String json = null;
                try {
                    json = OAuthService.getInstance().getResponse(url);
                    // final String json = Sample.JSON_LIST;
                } catch (HttpResponseException e) {
                    Log.w("JSON", e);
                    if (e.response.statusCode == 401) {
                        Preferences.removeToken(WorkitemListActivity.this);
                    }
                    showAlertDialogAndFinishApplication("Failed to connect to server.");
                    return;
                } catch (IOException e) {
                    Log.w("JSON", e);
                    showAlertDialogAndFinishApplication("Failed to connect to server.");
                    return;
                }
                if (!workitems.isEmpty()) {
                    workitems.clear();
                }
                try {
                    for (Workitem workitem : parser.parse(json)) {
                        workitems.add(workitem);
                    }
                } catch (JSONException e) {
                    Log.e(WorkitemListActivity.class.toString(),
                          e.getMessage(),
                          e);
                    showAlertDialogAndFinishApplication("Failed to parse data.");
                    return;
                }
                TextView textView = (TextView) findViewById(R.id.workitem_list_lastupdate);
                SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                textView.setText(getText(R.string.msg_last_update)
                        + format.format(new Date()));

                dialog.dismiss();

                Intent serviceIntent = new Intent(WorkitemListActivity.this,
                                                  StatsService.class);
                startService(serviceIntent);
            }
        });
    }

    /**
     * アラートダイアログを表示し、アプリケーションを終了させる
     * 
     * @param message
     */
    private void showAlertDialogAndFinishApplication(final String message) {
        handler.post(new Runnable() {
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(WorkitemListActivity.this);
                builder.setMessage(message);
                builder.setPositiveButton("Close application",
                                          new DialogInterface.OnClickListener() {
                                              public void onClick(DialogInterface arg0,
                                                                  int arg1) {
                                                  finish();
                                              }
                                          });
                builder.show();
            }
        });
    }

    /** Menu ID for Reload */
    private static final int MENU_RELOAD = 0;
    /** Menu ID for Quit */
    private static final int MENU_CLOSE = 1;
    /** Menu ID for Reset Config */
    private static final int MENU_SETTINGS = 2;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_RELOAD, 0, getText(R.string.menu_reload));
        menu.add(0, MENU_CLOSE, 0, getText(R.string.menu_close));
        menu.add(0, MENU_SETTINGS, 0, getText(R.string.menu_settings));
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_RELOAD :
                reloadList();
                break;
            case MENU_CLOSE :
                finish();
                break;
            case MENU_SETTINGS :
                Intent intent = new Intent(getApplicationContext(),
                                           SettingsActivity.class);
                startActivity(intent);
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        //        unregisterReceiver(receiver);
        //        Intent intent = new Intent(this, ConnectionService.class);
        //        stopService(intent);
        super.onDestroy();
    }
}